package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;
    @Resource
    UserMapper userMapper;
    @PostMapping
    public Result<?> save(@RequestBody User user){
        if (user.getPassword() == null){//默认密码
            user.setPassword("123468");
        }
        userService.insert(user);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody User user){

        userMapper.updateById(user);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize,@RequestParam(defaultValue = "") String searchStr){
        /**
         * searchStr 空字符串的处理 导入三方库 hutool
         */
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StringUtils.isNotBlank(searchStr)){//searchStr不为空，再设置为模糊查询
            wrapper.like(User::getNickname, searchStr);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        //拿到数据后渲染vue页面，传给tableData
        return Result.success(userPage);
    }

    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id){

        userMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (res == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (res != null){
            return Result.error("-1","用户名重复");
        }

        if (user.getPassword() == null){//默认密码
            user.setPassword("123468");
        }

        userService.insert(user);
        return Result.success();
    }
}
